package com.aeromedia.testcustomapplication

import android.app.Application
import android.os.Looper
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.aeromedia.vh_sdk.roomclient.action.GetStatesResp
import com.aeromedia.vh_sdk.ui.Call
import com.aeromedia.vh_sdk.ui.P2PSingleCall
import kotlinx.coroutines.launch

class FourCustomServiceViewModel(application: Application) : AndroidViewModel(application) {
    val userList: MutableLiveData<List<CustomServiceUser>> by lazy {
        MutableLiveData<List<CustomServiceUser>>(arrayListOf())
    }
    private val TAG = "FourCustomServiceViewMo"
    public fun getData() {
        Log.d(TAG, "getData: ")
        viewModelScope.launch {
            userListValue(loadData())
        }
    }

    fun userListValue(value: List<CustomServiceUser>) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            userList.value = value
        } else {
            userList.postValue(value)
        }
    }

    public fun updateData(res: GetStatesResp) {
        Log.d(TAG, "updateData: $res")
        val states = res.states
        val value = userList.value!!
        for (state in states) {
            value.forEach {
                if (state.termNumber == it.userId) {
                    if (state.platforms != null) {
                        it.state = CustomServiceUser.State.ONLINE
                        return@forEach
                    } else {
                        it.state = CustomServiceUser.State.OFFLINE
                    }

                }


            }
        }
        Log.d(TAG, "value: $value")
        userListValue(value)
    }

    private fun loadData(): List<CustomServiceUser> {
        val list = arrayListOf<CustomServiceUser>()
        val user1 = CustomServiceUser()
        user1.userName = "视频客服1"
        user1.userId = "00007777"
        list.add(user1)

        val user2 = CustomServiceUser()
        user2.userName = "视频客服2"
        user2.userId = "00008888"
        list.add(user2)

        val user3 = CustomServiceUser()
        user3.userName = "视频客服3"
        user3.userId = "00008889"
        list.add(user3)

        val user4 = CustomServiceUser()
        user4.userName = "视频客服4"
        user4.userId = "00008890"
        list.add(user4)

//        val user = CustomServiceUser()
//        user.userName = "视频客服 1163"
//        user.userId = "00001163"
//        list.add(user)
        return list
    }

    fun makeCall(number: String): Call {

        if (number.isNullOrBlank()) {
            throw Throwable("号码为空")
        }

        val call = when {
            number.length <= 8 -> {
                val aNumber = number.padStart(8, '0')
                P2PSingleCall(aNumber)
            }
            else -> {
                throw Throwable("被叫号码异常，请重新输入")
            }
        }

        return call
    }

}